<?php

namespace app\admin\controller;

use app\admin\model\CaAdminLog;
use app\common\controller\Backend;
use think\Config;
use think\Hook;
use think\Validate;
use think\Db;
/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['getCode','index', 'logout','ticket','admin_bind','change'];
    protected $layout = '';

    public function _initialize()
    {
//        if (strtolower(request()->action())=='ticket') return;
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 后台首页
     */
    public function index()
    {

        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
            'general'   => ['new', 'purple'],
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $id=session('admin.id');
        $group=0;
        if ($id==1 || $id==281  || $id==6  || $id==7){
            $res=DB::name('ca_auth_group_access')->where(['uid'=>$id])->find();
            if ($res['group_id']==13){
                $group='1';
            }else{
                $group='0';
            }

        }
        $this->assign('change',$group);

        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
//    public function login()
//    {
//        $url = $this->request->get('url', 'index/index');
//        if ($this->auth->isLogin()) {
//            $this->success(__("You've logged in, do not login again"), $url);
//        }
//        if ($this->request->isPost()) {
//            $username = $this->request->post('username');
//            $password = $this->request->post('password');
////            $keeplogin = $this->request->post('keeplogin');
//            $keeplogin = '1';
//            $token = $this->request->post('__token__');
////            dump($this->request->post(''));exit;
//            $rule = [
//                'username'  => 'require|length:3,50',
//                'password'  => 'require|length:3,30',
//                '__token__' => 'require|token',
//            ];
//            $data = [
//                'username'  => $username,
//                'password'  => $password,
//                '__token__' => $token,
//            ];
//            if (Config::get('fastadmin.login_captcha')) {
//                $rule['captcha'] = 'require|captcha';
//                $data['captcha'] = $this->request->post('captcha');
//            }
//            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
//            $result = $validate->check($data);
//            if (!$result) {
//                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
//            }
//            CaAdminLog::setTitle(__('Login'));
//            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
//            if ($result === true) {
//                Hook::listen("admin_login_after", $this->request);
//                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
//            } else {
//                $msg = $this->auth->getError();
//                $msg = $msg ? $msg : __('Username or password is incorrect');
//                $this->error($msg, $url, ['token' => $this->request->token()]);
//            }
//        }
//
//        // 根据客户端的cookie,判断是否可以自动登录
//        if ($this->auth->autologin()) {
//            $this->redirect($url);
//        }
//        $background = Config::get('fastadmin.login_background');
//        $background = $background ? (stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background) : '';
//        $this->view->assign('background', $background);
//        $this->view->assign('title', __('Login'));
//        Hook::listen("admin_login_init", $this->request);
//        return $this->view->fetch();
//    }
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $keeplogin = '1';
            $token = $this->request->post('__token__');
            $captcha=$this->request->post('captcha');
            $rule = [
                'username'  => 'require|length:3,50',
                '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                '__token__' => $token,
            ];
            if (!check_mobile($username))   $this->error('手机号输入有误');
            if (strlen($captcha) <> 6 && !empty($captcha))   $this->error('验证码输入有误');
            if ($captcha){
                $where['code'] = $captcha;
                $where['phone'] = $username;
                $where['status'] = 1;
                $where['type'] = 5;
                CaAdminLog::setTitle(__('Login'));
                $result = $this->auth->login($username,$captcha, $keeplogin ? 86400 : 0);
                if ($result === true) {
                    Hook::listen("admin_login_after", $this->request);
                    $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
                } else {
                    $msg = $this->auth->getError();
                    $msg = $msg ? $msg : __('Username or password is incorrect');
                    $this->error($msg, $url, ['token' => $this->request->token()]);
                }
                $sms = Db::name('zd_sms')->field('phone,code,status,send_time')->where($where)->order('send_time desc')->find();
                if ($sms){
                    if (time()-$sms['send_time']>300){
//                    if (time()-$sms['send_time']>30000000000000){
                        $this->error('验证码超时,请重新获取');
                        $update['status'] = 3;
                        Db::name('zd_sms')->where($where)->update($update);
                    }else{
                        $update['status'] = 2;
                        $update['use_time'] = time();
                        Db::name('zd_sms')->where($where)->update($update);
                        $validate = new Validate($rule, [], ['username' => __('Username'),  'captcha' => __('Captcha')]);
                        $result = $validate->check($data);
                        if (!$result) {
                            $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
                        }
                        CaAdminLog::setTitle(__('Login'));
                        $result = $this->auth->login($username,$captcha, $keeplogin ? 86400 : 0);
                        if ($result === true) {
                            Hook::listen("admin_login_after", $this->request);
                            $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
                        } else {
                            $msg = $this->auth->getError();
                            $msg = $msg ? $msg : __('Username or password is incorrect');
                            $this->error($msg, $url, ['token' => $this->request->token()]);
                        }
                    }
                }else{
                    $this->error('验证码输入有误或验证码过期');
                }
            }

        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = $background ? (stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background) : '';
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }
    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        Hook::listen("admin_logout_after", $this->request);
        $this->success(__('Logout successful'), 'index/login');
    }

//    /*检查KEY状态*/
//    public function ticket()
//    {
//        if ($this->request->isAjax()) {
//            $type=input('post.type');
//            $state=input('post.state');
//            if ($type=='login' && $state){
//                $time=strtotime(date("Y-m-d"),time());
//                $res= Db::name('ca_admin_scan')->where(['state'=>$state])->where("time>=".$time."")->find();
//
//                if ($res){
//                    $data=Db::name('ca_admin')->field('username')->where(['wx_token'=>$res['open_id'],'status'=>'normal'])->find();
//                    if ($data){
//                        CaAdminLog::setTitle(__('扫码登录'));
//                        $keeplogin='1';
//                        $result = $this->auth->login($data['username'],0, $keeplogin ? 86400 : 0);
//                        if ($result === true) {
//                            Hook::listen("admin_login_after", $this->request);
//                        } else {
//                            $msg = $this->auth->getError();
//                            $msg = $msg ? $msg : __('Username or password is incorrect');
//                            return['status'=>400,'msg'=>$msg];
//                        }
//                        return['status'=>200,'msg'=>'授权成功，登录中...'];
//                    }else{
//                        return['status'=>201,'msg'=>'授权成功，请先绑定账号...','data'=>$state];
//                    }
//                }else{
//                    return['status'=>400,'msg'=>'未扫码'];
//                }
//            }else{
//                return['status'=>400,'msg'=>'未知错误'];
//            }
//
//        }
//    }
    public function curlPost($url, $data = null)
    {
        //创建一个新cURL资源
        $curl = curl_init();
        //设置URL和相应的选项
        curl_setopt($curl, CURLOPT_URL, $url);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行curl，抓取URL并把它传递给浏览器
        $output = curl_exec($curl);
        //关闭cURL资源，并且释放系统资源
        curl_close($curl);
        return $output;
    }
    /*检查KEY状态*/
    public function ticket()
    {
        $type=input('post.type');
        $state=input('post.state');

        $url='http://admin.gkzzd.cn/dMyrxOzYpf.php/extend/wechat/ticket_api';
        $params = ['type'=>$type,'state'=>$state];
        $result = $this->curlPost($url,$params);

        echo $result;
    }

    public function admin_bind(){
        if ($this->request->isAjax()) {
            $state=input('post.state');
            $code=input('post.code');
            $phone=input('post.phone');
            if ($state && $phone && $code){
                $time=strtotime(date("Y-m-d"),time());
                $res= Db::name('ca_admin_scan')->where(['state'=>$state])->where("time>=".$time."")->find();
                if ($res){
                    $where['code'] = $code;
                    $where['phone'] = $phone;
                    $where['status'] = 1;
                    $where['type'] = 6;
                    $sms = Db::name('zd_sms')->field('phone,code,status,send_time')->where($where)->order('send_time desc')->find();
                    if ($sms){
                        if (time()-$sms['send_time']>300){
                            $this->error('验证码超时,请重新获取');
                            $update['status'] = 3;
                            Db::name('zd_sms')->where($where)->update($update);
                        }else{
                            $update['status'] = 2;
                            $update['use_time'] = time();
                            Db::name('zd_sms')->where($where)->update($update);
                            $data1=Db::name('ca_admin')->field('username,id')->where(['username'=>$phone,'status'=>'normal'])->find();
                            if ($data1){
                                $data=Db::name('ca_admin')->field('username')->where(['wx_token'=>$res['open_id'],'status'=>'normal'])->find();
                                if ($data){
                                    return['status'=>300,'msg'=>'该微信已绑定过，请联系管理员'];
                                }else{
                                    Db::name('ca_admin')->where(['username'=>$phone])->update(['wx_token'=>$res['open_id']]);
                                    Db::name('ca_admin_bind')->insert(['phone'=>$phone,'code'=>$code,'open_id'=>$res['open_id'],'m_id'=>$data1['id'],'time'=>time()]);
                                    CaAdminLog::setTitle(__('扫码登录'));
                                    $keeplogin='1';
                                    $result = $this->auth->login($phone,0, $keeplogin ? 86400 : 0);
                                    if ($result === true) {
                                        Hook::listen("admin_login_after", $this->request);
                                    } else {
                                        $msg = $this->auth->getError();
                                        $msg = $msg ? $msg : __('Username or password is incorrect');
                                        return['status'=>400,'msg'=>$msg];
                                    }
                                    return['status'=>200,'msg'=>'绑定成功，登录中...'];

                                }
                            }else{
                                return['status'=>400,'msg'=>'该手机号未注册，请点击申请开通后台权限'];
                            }
                        }
                    }else{
                        return['status'=>400,'msg'=>'验证码错误'];
                    }
                }else{
                    return['status'=>400,'msg'=>'未知错误，请刷新后再扫码'];
                }
            }else{
                return['status'=>400,'msg'=>'未知错误'];
            }
        }
    }

    public function change(){
        $id=session('admin.id');
        if ($id==1 || $id==281  || $id==6  || $id==7){
            $flag=input('post.flag');
            if ($flag=='0'){
                $update='1';
                $group=13;
            }else{
                $update='0';
                switch ($id){
                    case 1:
                        $group=1;
                        break;
                    case 6:
                        $group=2;
                        break;
                    case 7:
                        $group=2;
                        break;
                    case 281:
                        $group=19;
                        break;
                }
            }
            $res=DB::name('ca_admin')->where(['id'=>$id])->update(['type'=>$update]);
            if ($res){
                DB::name('ca_auth_group_access')->where(['uid'=>$id])->update(['group_id'=>$group]);
                return['code'=>1,'msg'=>'切换成功'];
            }
        }else{
            return['code'=>0,'msg'=>'非法访问'];
        }
    }
}
